package cn.itcast.email;

import cn.itcast.utils.MailUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.util.Map;

public class EmailConsumer implements MessageListener {

    @Autowired
    private JavaMailSender javaMailSender;

    public void setJavaMailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public void onMessage(Message message) {
        byte[] body = message.getBody();  // 就是我们向mq中存放的内容 map
//        把字节数组转成map  可以直接使用一个阿里巴巴提供工具类
        Map<String,String> map = JSON.parseObject(body, Map.class);
        String to = map.get("to");
        String subject = map.get("subject");
        String content = map.get("content");
        try {
//            MailUtil.sendMsg(to,subject,content);
            this. sendEmai(to,subject,content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    普通邮件
    public void sendEmai(String to ,String subject ,String content) throws Exception{
//        看做邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        给邮件设置接收人、主题、内容
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content);
        helper.setFrom("itcast_server@sina.com");
        javaMailSender.send(mimeMessage);
        System.out.println("发送成功。。。。。。");
    }
}
